document.addEventListener('DOMContentLoaded', function() {
    // 获取视图类型选项
    fetch('/api/get_view_types')
        .then(response => response.json())
        .then(data => {
            const viewTypeSelects = document.querySelectorAll('.view-type');
            viewTypeSelects.forEach(select => {
                data.view_types.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type;
                    option.textContent = type;
                    select.appendChild(option);
                });
            });
        })
        .catch(error => console.error('获取视图类型失败:', error));
    
    // 生成JSON文件按钮点击事件
    document.getElementById('generateBtn').addEventListener('click', function(e) {
        e.preventDefault();
        
        // 收集所有子视图数据
        const subviews = [];
        document.querySelectorAll('.subview-item').forEach(item => {
            const subview = collectSubviewData(item);
            if (subview) {
                subviews.push(subview);
            }
        });
        
        // 收集基本配置
        const config = {
            class_type_index: document.getElementById('classType').value,
            module: document.getElementById('module').value,
            prefix: document.getElementById('prefix').value,
            class_desc: document.getElementById('classDesc').value,
            file_name: document.getElementById('fileName').value,
            subviews: subviews
        };
        
        console.log('发送的配置数据:', config); // 调试用
        
        // 发送请求到后端
        fetch('/api/create_json', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(config)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            // 显示结果消息
            document.getElementById('resultArea').style.display = 'block';
            document.getElementById('resultMessage').textContent = `JSON文件已生成: ${data.path}`;
            
            // 更新JSON预览
            fetch(`/api/get_json?filepath=${encodeURIComponent(data.path)}`)
                .then(response => response.json())
                .then(jsonData => {
                    document.getElementById('jsonPreview').textContent = JSON.stringify(jsonData, null, 2);
                })
                .catch(error => console.error('获取JSON内容失败:', error));
        })
        .catch(error => {
            console.error('生成JSON文件失败:', error);
            document.getElementById('resultArea').style.display = 'block';
            document.getElementById('resultMessage').textContent = '生成JSON文件失败，请查看控制台获取详细信息。';
            document.getElementById('resultMessage').className = 'alert alert-danger';
        });
    });
    
    // 收集子视图数据的辅助函数
    function collectSubviewData(subviewItem) {
        const viewType = subviewItem.querySelector('.view-type').value;
        if (!viewType) return null;
        
        const viewDesc = subviewItem.querySelector('.view-desc').value;
        
        // 收集属性
        const properties = {};
        subviewItem.querySelectorAll('[class*="prop-"]').forEach(prop => {
            const classNames = prop.className.split(' ');
            let propName = '';
            
            for (const className of classNames) {
                if (className.startsWith('prop-')) {
                    propName = className.replace('prop-', '');
                    break;
                }
            }
            
            if (propName) {
                if (prop.type === 'checkbox') {
                    properties[propName] = prop.checked;
                } else if (prop.type === 'number') {
                    properties[propName] = parseFloat(prop.value);
                } else {
                    properties[propName] = prop.value;
                }
            }
        });
        
        // 收集约束条件
        const constraints = {};
        const constraintFields = ['top', 'leading', 'trailing', 'bottom', 'centerX', 'centerY', 'width', 'height'];
        constraintFields.forEach(field => {
            const enabledCheckbox = subviewItem.querySelector(`.constraint-${field}-enabled`);
            const valueInput = subviewItem.querySelector(`.constraint-${field}`);
            if (enabledCheckbox && enabledCheckbox.checked && valueInput) {
                constraints[field] = parseFloat(valueInput.value);
            }
        });
        
        return {
            view_type: viewType,
            view_des: viewDesc,
            properties: properties,
            constraints: constraints
        };
    }
    
    // 添加子视图按钮点击事件
    // 删除重复的事件监听器设置
    // 这些事件监听器已经在setupAutoUpdate函数中设置过
    document.getElementById('addSubview').addEventListener('click', function() {
        const template = document.getElementById('subviewTemplate');
        const clone = document.importNode(template.content, true);
        
        // 设置折叠按钮的目标
        const collapseId = 'collapse-' + Date.now();
        const propertiesBtn = clone.querySelector('.toggle-properties');
        const propertiesContainer = clone.querySelector('.properties-container');
        propertiesBtn.setAttribute('data-bs-target', '#' + collapseId);
        propertiesContainer.id = collapseId;
        
        const constraintsCollapseId = 'constraints-' + Date.now();
        const constraintsBtn = clone.querySelector('.toggle-constraints');
        const constraintsContainer = clone.querySelector('.constraints-container');
        constraintsBtn.setAttribute('data-bs-target', '#' + constraintsCollapseId);
        constraintsContainer.id = constraintsCollapseId;
        
        // 添加到容器
        document.getElementById('subviewsContainer').appendChild(clone);
        
        // 设置视图类型变更事件
        const viewTypeSelect = document.querySelector('#subviewsContainer .subview-item:last-child .view-type');
        viewTypeSelect.addEventListener('change', function() {
            const subviewItem = this.closest('.subview-item');
            updateSpecificProps(subviewItem, this.value);
        });
        
        // 设置透明度滑块事件
        const alphaSlider = document.querySelector('#subviewsContainer .subview-item:last-child .prop-alpha');
        const alphaValue = document.querySelector('#subviewsContainer .subview-item:last-child .alpha-value');
        alphaSlider.addEventListener('input', function() {
            alphaValue.textContent = this.value;
        });
        
        // 设置保存按钮事件
        const saveBtn = document.querySelector('#subviewsContainer .subview-item:last-child .save-subview');
        saveBtn.addEventListener('click', function() {
            const subviewItem = this.closest('.subview-item');
            const saveMessage = subviewItem.querySelector('.badge');
            saveMessage.classList.remove('d-none');
            setTimeout(() => {
                saveMessage.classList.add('d-none');
            }, 2000);
        });
        
        // 设置删除按钮事件
        const removeBtn = document.querySelector('#subviewsContainer .subview-item:last-child .remove-subview');
        removeBtn.addEventListener('click', function() {
            const subviewItem = this.closest('.subview-item');
            subviewItem.remove();
        });
    });
    
    // 更新特定视图类型的属性
    function updateSpecificProps(subviewItem, viewType) {
        const specificProps = subviewItem.querySelectorAll('.specific-props > div');
        specificProps.forEach(prop => prop.classList.add('d-none'));
        
        if (viewType === 'UILabel') {
            subviewItem.querySelector('.label-props').classList.remove('d-none');
        } else if (viewType === 'UIButton') {
            subviewItem.querySelector('.button-props').classList.remove('d-none');
        } else if (viewType === 'UIImageView') {
            subviewItem.querySelector('.imageview-props').classList.remove('d-none');
        }
    }
    
    // 下载JSON按钮点击事件
    document.getElementById('downloadJson').addEventListener('click', function() {
        const jsonContent = document.getElementById('jsonPreview').textContent;
        if (!jsonContent) {
            alert('没有可下载的JSON内容，请先生成JSON文件');
            return;
        }
        
        const blob = new Blob([jsonContent], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = document.getElementById('fileName').value + '.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    });
    
    // 生成Swift代码按钮点击事件
    document.getElementById('generateSwift').addEventListener('click', function() {
        const jsonContent = document.getElementById('jsonPreview').textContent;
        if (!jsonContent) {
            alert('请先生成JSON文件');
            return;
        }
        
        fetch('/api/generate_swift', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: jsonContent
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`Swift代码已生成: ${data.path}`);
            } else {
                alert('生成Swift代码失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('生成Swift代码失败:', error);
            alert('生成Swift代码失败，请查看控制台获取详细信息');
        });
    });
    
    // 保存所有子视图按钮点击事件
    document.getElementById('saveAllSubviews').addEventListener('click', function() {
        document.querySelectorAll('.subview-item .save-subview').forEach(btn => btn.click());
        const globalSaveMessage = document.getElementById('globalSaveMessage');
        globalSaveMessage.classList.remove('d-none');
        setTimeout(() => {
            globalSaveMessage.classList.add('d-none');
        }, 2000);
    });
});

// 页面加载时获取视图类型和类型数据
document.addEventListener('DOMContentLoaded', function() {
    // 获取视图类型和类型数据
    fetch('/api/get_view_types')
        .then(response => response.json())
        .then(data => {
            // 保存视图类型数据，用于后续添加子视图时使用
            window.viewTypes = data.view_types;
            
            // 更新所有视图类型选择框
            const viewTypeSelects = document.querySelectorAll('.view-type');
            viewTypeSelects.forEach(select => {
                updateViewTypeOptions(select);
            });
            
            // 填充类型选择框
            const classTypeSelect = document.getElementById('classType');
            if (classTypeSelect) {
                classTypeSelect.innerHTML = ''; // 清空现有选项
                
                data.class_types.forEach((type, index) => {
                    const option = document.createElement('option');
                    option.value = index;
                    option.textContent = type;
                    classTypeSelect.appendChild(option);
                });
            }
            
            // 初始化JSON预览
            updateJsonPreview();
        })
        .catch(error => {
            console.error('获取视图类型数据失败:', error);
            alert('获取视图类型数据失败，请刷新页面重试');
        });
        
    // 为所有输入元素添加事件监听器，实现自动更新
    setupAutoUpdate();
    
    // 视图类型变更时，显示/隐藏对应的特定属性
    document.addEventListener('change', function(event) {
        if (event.target.classList.contains('view-type')) {
            const viewType = event.target.value;
            const subviewItem = event.target.closest('.subview-item');
            if (subviewItem) {
                // 隐藏所有特定属性
                const specificProps = subviewItem.querySelectorAll('.specific-props > div');
                specificProps.forEach(prop => prop.classList.add('d-none'));
                
                // 显示对应的特定属性
                if (viewType === 'UILabel') {
                    subviewItem.querySelector('.label-props')?.classList.remove('d-none');
                } else if (viewType === 'UIButton') {
                    subviewItem.querySelector('.button-props')?.classList.remove('d-none');
                } else if (viewType === 'UIImageView') {
                    subviewItem.querySelector('.imageview-props')?.classList.remove('d-none');
                }
            }
            
            // 更新JSON预览
            updateJsonPreview();
        }
    });
});

// 更新视图类型选择框的选项
function updateViewTypeOptions(selectElement) {
    if (window.viewTypes && window.viewTypes.length > 0) {
        selectElement.innerHTML = ''; // 清空现有选项
        
        window.viewTypes.forEach(type => {
            const option = document.createElement('option');
            option.value = type;
            option.textContent = type;
            selectElement.appendChild(option);
        });
    }
}

// 设置自动更新
function setupAutoUpdate() {
    // 监听基本配置表单的所有输入变化
    const configForm = document.getElementById('configForm');
    if (configForm) {
        const inputs = configForm.querySelectorAll('input, select');
        inputs.forEach(input => {
            input.addEventListener('change', updateJsonPreview);
            input.addEventListener('input', updateJsonPreview);
        });
    }
    
    // 监听添加子视图按钮
    const addSubviewBtn = document.getElementById('addSubview');
    if (addSubviewBtn) {
        addSubviewBtn.addEventListener('click', function() {
            addSubview();
            updateJsonPreview();
        });
    }
    
    // 委托事件监听，处理子视图的输入变化
    document.addEventListener('change', function(event) {
        const target = event.target;
        if (target.closest('.subview-item')) {
            updateJsonPreview();
        }
    });
    
    document.addEventListener('input', function(event) {
        const target = event.target;
        if (target.closest('.subview-item')) {
            updateJsonPreview();
        }
    });
    
    // 委托事件监听，处理删除子视图
    document.addEventListener('click', function(event) {
        const target = event.target;
        if (target.classList.contains('remove-subview')) {
            const subviewItem = target.closest('.subview-item');
            if (subviewItem) {
                subviewItem.remove();
                updateJsonPreview();
            }
        }
    });
}

// 添加子视图
function addSubview() {
    const template = document.getElementById('subviewTemplate');
    const container = document.getElementById('subviewsContainer');
    
    if (template && container) {
        const clone = document.importNode(template.content, true);
        
        // 设置折叠面板的唯一ID
        const uniqueId = 'collapse-' + Date.now();
        const propertiesBtn = clone.querySelector('.toggle-properties');
        const propertiesContainer = clone.querySelector('.properties-container');
        
        if (propertiesBtn && propertiesContainer) {
            propertiesBtn.setAttribute('data-bs-target', '#' + uniqueId);
            propertiesContainer.id = uniqueId;
        }
        
        // 设置约束条件折叠面板的唯一ID
        const constraintsUniqueId = 'constraints-' + Date.now();
        const constraintsBtn = clone.querySelector('.toggle-constraints');
        const constraintsContainer = clone.querySelector('.constraints-container');
        
        if (constraintsBtn && constraintsContainer) {
            constraintsBtn.setAttribute('data-bs-target', '#' + constraintsUniqueId);
            constraintsContainer.id = constraintsUniqueId;
        }
        
        // 更新视图类型选择框
        const viewTypeSelect = clone.querySelector('.view-type');
        if (viewTypeSelect) {
            updateViewTypeOptions(viewTypeSelect);
        }
        
        container.appendChild(clone);
    }
}

// 更新JSON预览
function updateJsonPreview() {
    // 获取基本配置
    const classTypeIndex = document.getElementById('classType')?.value || 0;
    const module = document.getElementById('module')?.value || 'Login';
    const prefix = document.getElementById('prefix')?.value || 'CAT';
    const classDesc = document.getElementById('classDesc')?.value || '登录页';
    
    // 获取所有子视图配置
    const subviews = [];
    const subviewItems = document.querySelectorAll('.subview-item');
    
    subviewItems.forEach(item => {
        const viewType = item.querySelector('.view-type')?.value;
        const viewDesc = item.querySelector('.view-desc')?.value || '';
        
        if (viewType) {
            // 创建子视图对象
            const subview = {
                viewType: viewType
            };
            
            // 只有当描述不为空时才添加
            if (viewDesc) {
                subview.desc = viewDesc;
            }
            
            // 获取通用属性（只添加非默认值）
            const properties = {};
            
            // 背景颜色，默认值为rgba(0, 0, 0, 1)
            const backgroundColor = item.querySelector('.prop-backgroundColor')?.value;
            if (backgroundColor && backgroundColor !== 'rgba(0, 0, 0, 1)') {
                properties.backgroundColor = backgroundColor;
            }
            
            // 透明度，默认值为1.0
            const alpha = parseFloat(item.querySelector('.prop-alpha')?.value || 1.0);
            if (alpha !== 1.0) {
                properties.alpha = alpha;
            }
            
            // 隐藏状态，默认值为false
            const isHidden = item.querySelector('.prop-isHidden')?.checked || false;
            if (isHidden) {
                properties.isHidden = isHidden;
            }
            
            // 裁剪子视图，默认值为false
            const clipsToBounds = item.querySelector('.prop-clipsToBounds')?.checked || false;
            if (clipsToBounds) {
                properties.clipsToBounds = clipsToBounds;
            }
            
            // 标签值，默认值为0
            const tag = parseInt(item.querySelector('.prop-tag')?.value || 0);
            if (tag !== 0) {
                properties.tag = tag;
            }
            
            // 用户交互，默认值为true
            const isUserInteractionEnabled = item.querySelector('.prop-isUserInteractionEnabled')?.checked !== false;
            if (!isUserInteractionEnabled) {
                properties.isUserInteractionEnabled = isUserInteractionEnabled;
            }
            
            // 内容模式，默认值为scaleAspectFit
            const contentMode = item.querySelector('.prop-contentMode')?.value;
            if (contentMode && contentMode !== 'scaleAspectFit') {
                properties.contentMode = contentMode;
            }
            
            // 圆角半径，默认值为0
            const cornerRadius = parseInt(item.querySelector('.prop-cornerRadius')?.value || 0);
            if (cornerRadius !== 0) {
                properties.cornerRadius = cornerRadius;
            }
            
            // 边框宽度，默认值为0
            const borderWidth = parseInt(item.querySelector('.prop-borderWidth')?.value || 0);
            if (borderWidth !== 0) {
                properties.borderWidth = borderWidth;
            }
            
            // 边框颜色，默认值为rgba(0, 0, 0, 1)
            const borderColor = item.querySelector('.prop-borderColor')?.value;
            if (borderColor && borderColor !== 'rgba(0, 0, 0, 1)') {
                properties.borderColor = borderColor;
            }
            
            // 获取特定视图类型的属性（只添加非默认值）
            if (viewType === 'UILabel') {
                const text = item.querySelector('.prop-text')?.value;
                if (text && text !== '标签') {
                    properties.text = text;
                }
                
                const textColor = item.querySelector('.prop-textColor')?.value;
                if (textColor && textColor !== 'rgba(0, 0, 0, 1)') {
                    properties.textColor = textColor;
                }
                
                const fontSize = parseInt(item.querySelector('.prop-fontSize')?.value || 16);
                if (fontSize !== 16) {
                    properties.fontSize = fontSize;
                }
                
                const fontWeight = item.querySelector('.prop-fontWeight')?.value;
                if (fontWeight && fontWeight !== 'regular') {
                    properties.fontWeight = fontWeight;
                }
                
                const numberOfLines = parseInt(item.querySelector('.prop-numberOfLines')?.value || 1);
                if (numberOfLines !== 1) {
                    properties.numberOfLines = numberOfLines;
                }
                
                const textAlignment = item.querySelector('.prop-textAlignment')?.value;
                if (textAlignment && textAlignment !== 'left') {
                    properties.textAlignment = textAlignment;
                }
            } else if (viewType === 'UIButton') {
                const title = item.querySelector('.prop-title')?.value;
                if (title && title !== '按钮') {
                    properties.title = title;
                }
                
                const titleColor = item.querySelector('.prop-titleColor')?.value;
                if (titleColor && titleColor !== 'rgba(0, 0, 0, 1)') {
                    properties.titleColor = titleColor;
                }
                
                const fontSize = parseInt(item.querySelector('.prop-fontSize')?.value || 16);
                if (fontSize !== 16) {
                    properties.fontSize = fontSize;
                }
                
                const fontWeight = item.querySelector('.prop-fontWeight')?.value;
                if (fontWeight && fontWeight !== 'medium') {
                    properties.fontWeight = fontWeight;
                }
                
                const action = item.querySelector('.prop-action')?.value;
                if (action && action !== 'buttonTapped') {
                    properties.action = action;
                }
            } else if (viewType === 'UIImageView') {
                const image = item.querySelector('.prop-image')?.value;
                if (image) {
                    properties.image = image;
                }
            }
            
            // 只有当有属性时才添加
            if (Object.keys(properties).length > 0) {
                subview.properties = properties;
            }
            
            // 获取约束条件（只添加启用的约束）
            const constraints = {};
            
            if (item.querySelector('.constraint-top-enabled')?.checked) {
                constraints.top = parseInt(item.querySelector('.constraint-top')?.value || 0);
            }
            
            if (item.querySelector('.constraint-leading-enabled')?.checked) {
                constraints.leading = parseInt(item.querySelector('.constraint-leading')?.value || 0);
            }
            
            if (item.querySelector('.constraint-centerX-enabled')?.checked) {
                constraints.centerX = parseInt(item.querySelector('.constraint-centerX')?.value || 0);
            }
            
            if (item.querySelector('.constraint-centerY-enabled')?.checked) {
                constraints.centerY = parseInt(item.querySelector('.constraint-centerY')?.value || 0);
            }
            
            if (item.querySelector('.constraint-bottom-enabled')?.checked) {
                constraints.bottom = parseInt(item.querySelector('.constraint-bottom')?.value || 0);
            }
            
            if (item.querySelector('.constraint-trailing-enabled')?.checked) {
                constraints.trailing = parseInt(item.querySelector('.constraint-trailing')?.value || 0);
            }
            
            if (item.querySelector('.constraint-width-enabled')?.checked) {
                constraints.width = parseInt(item.querySelector('.constraint-width')?.value || 0);
            }
            
            if (item.querySelector('.constraint-height-enabled')?.checked) {
                constraints.height = parseInt(item.querySelector('.constraint-height')?.value || 0);
            }
            
            // 只有当有约束条件时才添加
            if (Object.keys(constraints).length > 0) {
                subview.constraints = constraints;
            }
            
            subviews.push(subview);
        }
    });
    
    // 创建JSON对象（只包含必要的字段）
    const jsonData = {
        classType: document.querySelector(`#classType option[value="${classTypeIndex}"]`)?.textContent || 'UIView',
        moudle: module,
        prefix: prefix,
        classDesc: classDesc
    };
    
    // 只有当有子视图时才添加
    if (subviews.length > 0) {
        jsonData.subviews = subviews;
    }
    
    // 更新JSON预览
    const jsonPreview = document.getElementById('jsonPreview');
    if (jsonPreview) {
        jsonPreview.textContent = JSON.stringify(jsonData, null, 2);
    }
}

// 下载JSON文件
document.getElementById('downloadJson')?.addEventListener('click', function() {
    const jsonPreview = document.getElementById('jsonPreview');
    if (jsonPreview && jsonPreview.textContent) {
        const fileName = document.getElementById('fileName')?.value || 'config';
        const blob = new Blob([jsonPreview.textContent], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName + '.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
});

// 生成Swift代码
document.getElementById('generateSwift')?.addEventListener('click', function() {
    const jsonPreview = document.getElementById('jsonPreview');
    if (jsonPreview && jsonPreview.textContent) {
        // 先保存JSON文件到服务器
        const jsonData = JSON.parse(jsonPreview.textContent);
        const fileName = document.getElementById('fileName')?.value || 'config';
        
        fetch('/api/create_json', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                class_type_index: document.getElementById('classType')?.value || 0,
                module: jsonData.moudle,
                prefix: jsonData.prefix,
                class_desc: jsonData.classDesc,
                file_name: fileName,
                subviews: jsonData.subviews || []
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 调用生成Swift代码的API
                return fetch('/api/generate_swift', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        json_path: data.path
                    })
                });
            } else {
                throw new Error(data.message);
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Swift代码生成成功: ' + data.path);
            } else {
                alert('生成Swift代码失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('生成Swift代码失败:', error);
            alert('生成Swift代码失败: ' + error.message);
        });
    }
});
